package com.jeejio.common.util

import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager

/**
 * Author: JFangZ
 * Email: janezhang1901@163.com
 * Date: 2021/5/7 14:20
 * Description:
 */
object FragmentUtil {
    /**
     * Author: JFangZ
     * Email: janezhang1901@163.com
     * Date:2021/5/7 14:24
     * Description:Show specified fragment if exists,Add fragment if not exists.
     */
    fun showFragment(fragmentManager: FragmentManager, containerId: Int, showFragment: Fragment?, bundle: Bundle? = null): Fragment? {
        if (showFragment == null) {
            throw NullPointerException("The Fragment to be displayed can not be null")
        }
        val fragmentTransaction = fragmentManager.beginTransaction()
        val fragmentList = fragmentManager.fragments
        for (fragment in fragmentList) {
            fragmentTransaction.hide(fragment)
        }
        if (checkFragment(fragmentManager, showFragment)) {
            if (bundle != null) {
                showFragment.arguments = bundle
            }
            fragmentTransaction.show(showFragment)
        } else {
            if (bundle != null) {
                showFragment.arguments = bundle
            }
            fragmentTransaction.add(containerId, showFragment, showFragment.javaClass.simpleName + "_" + showFragment.hashCode())
        }
        fragmentTransaction.commitNowAllowingStateLoss()
        return showFragment
    }

    /**
     * Author: JFangZ
     * Email: janezhang1901@163.com
     * Date:2021/5/7 14:24
     * Description:Add specified fragment but doesn't show.
     */
    fun addFragment(fragmentManager: FragmentManager, containerId: Int, addFragment: Fragment) {
        fragmentManager.beginTransaction().add(containerId, addFragment, addFragment.javaClass.simpleName + "_" + addFragment.hashCode())
                .hide(addFragment)
                .commitNowAllowingStateLoss()
    }

    /**
     * Author: JFangZ
     * Email: janezhang1901@163.com
     * Date:2021/5/7 14:24
     * Description:Remove specified fragment if exists.
     */
    fun removeFragment(fragmentManager: FragmentManager, removeFragment: Fragment) {
        val fragmentByTag = fragmentManager.findFragmentByTag(removeFragment.javaClass.simpleName + "_" + removeFragment.hashCode())
                ?: return
        fragmentManager.beginTransaction().remove(fragmentByTag)
                .commitNowAllowingStateLoss()
    }

    /**
     * Author: JFangZ
     * Email: janezhang1901@163.com
     * Date:2021/5/7 14:24
     * Description:Check specified fragment exists or not.
     */
    fun checkFragment(fragmentManager: FragmentManager, checkFragment: Fragment): Boolean {
        return fragmentManager.findFragmentByTag(checkFragment.javaClass.simpleName + "_" + checkFragment.hashCode()) != null
    }
}